package com.ck.xs.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 文件工具类
 *
 * @author xiaosun
 * @ctime 20190824
 */
public class FileUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 新建文件
     * @param path 文件路径
     * @return
     */
    public static boolean createNewFile(String path) {
        try {
            String[] lists=path.split("\\.");
            int lastLength=lists[0].lastIndexOf("\\");
            int lastLengthSplit = lists[0].lastIndexOf("/");
            if(lastLengthSplit>0){
                lastLength = lastLengthSplit;
            }
            //得到文件夹目录
            String dir=lists[0].substring(0, lastLength);
            //得到文件名称
            String fileName=lists[0].substring(lastLength);
            //得到路径e:\a\b之后,先创建文件夹
            if(createMultilayerFile(dir)==true)
            {
                File filePath = new File(path);
                if (!filePath.exists()) {
                    filePath.createNewFile();
                }
            }
            return true;
        } catch (Exception e) {
            //System.out.println("新建文件操作出错: "+e.getMessage());
            LOGGER.error(e.getMessage());
        }
        return false;
    }
    /**
     * 创建文件夹--多层
     * @param dir 目录
     * @return
     */
    public static boolean createMultilayerFile(String dir) {
        try {
            File dirPath = new File(dir);
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }
        } catch (Exception e) {
            //System.out.println("创建多层目录操作出错: "+e.getMessage());
            LOGGER.error(e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 判断文件是否存在
     * @param fileUrl
     * @return 存在 true |false
     */
    public static boolean isExitsFile(String fileUrl){
        if(CheckUtil.isNull(fileUrl)){
            return false;
        }
        try{
            File file = new File(fileUrl);
            if(file.exists()){
                return true;
            }
        }catch (Exception e){
            LOGGER.error("isExitsFile===>{}",e.getMessage());
        }
        return false;
    }
    /**
     * 判断文件是否存在
     * @param file
     * @return
     */
    public static boolean isFileExits(File file){
        if(null == file){
            return false;
        }
        try{
            return file.exists();
        }catch (Exception e){
            LOGGER.error("isFileExits===>{}",e.getMessage());
        }
        return false;
    }

    /**
     * 读取json文件，返回json串
     * @param fileName 文件路径
     * @return
     */
    public static String readJsonFile(String fileName) {
        if(CheckUtil.isNull(fileName)){
            return null;
        }
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);

            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            LOGGER.error("读取json文件失败");
            return null;
        }
    }

    /**
     * 获取某个资源文件路径，如果没有传递则返回整个目录
     * @param properties /xxx.xx
     * @return
     */
    public static String getProjectResourcesUrl(String properties){
        String result = "";
        try{
            if(CheckUtil.isNull(properties)){
                result = FileUtil.class.getResource("/").getPath();
            }else{
                result = FileUtil.class.getResource(properties).getPath();
            }
        }catch (Exception e){
            LOGGER.error("获取资源文件路径失败");
        }
        return result;
    }
    /**
     * 获取流：this.getClass().getResourceAsStream(“/other/mrmy.properties”)，返回值：InputStream
     * ，如果没有传递则返回整个目录
     * @param properties /xxx.xx
     * @return
     */
    public static InputStream getProjectResourcesInputStreamUrl(String properties){
        InputStream result = null;
        try{
            if(CheckUtil.isNull(properties)){
                result = FileUtil.class.getResourceAsStream("/");
            }else{
                result = FileUtil.class.getResourceAsStream(properties);
            }
        }catch (Exception e){
            LOGGER.error("获取资源文件路径失败");
        }
        return result;
    }

    /**
     * 根据文件获取路径
     * @param file
     * @return
     */
    public static String getFileDir(File file){
        String path = file.getPath();
        if(CheckUtil.isNull(path)){
            return null;
        }
        if(path.contains("\\")){
            path = path.substring(0,path.lastIndexOf("\\")+1);
        }else{
            path = path.substring(0,path.lastIndexOf("/")+1);
        }
        return path;
    }
    /**
     * 根据文件获取路径
     * @param url
     * @return
     */
    public static String getUrlHost(String url){
        String path = url;
        String pattern = "http://[^//]*?\\.(com|cn|net|org|biz|info|cc|tv)" ;
        if(url.contains("index.m3u8")){
            path = url.substring(0,url.lastIndexOf("index.m3u8"));
        }else{
            if(url.contains("https")){
                pattern = "https://[^//]*?\\.(com|cn|net|org|biz|info|cc|tv)" ;
            }
            Pattern p = Pattern.compile(pattern,Pattern.CASE_INSENSITIVE);
            Matcher matcher = p.matcher(url);
            matcher.find();
            path = matcher.group();
        }
        return path;
    }

    /**
     *
     * @param s1 网址
     * @param _m3url m3
     * @return
     */
    public static String getTsFileUrl(String s1,String _m3url){
        String result = null;
        String[] m3UrlArr = _m3url.split("/");
        if(m3UrlArr.length>0){

        }else{

        }
        return result;
    }

    public static void main(String[] args){
    }
}
